<template>
    <div class="whiteboard">
        <div class="toolbar" id="toolbar">
            <div class="container">
                <div class="row">
                    <div class="menu-item" v-bind:class="[{active: tool == 'color'}, brush.color]">
                        <span class="menu-item-group" v-on:click="active('color')">
                            <span class="show brush-color"><icon class="icon" name="color" scale="20"></icon></span>
                        </span>
                        <span class="menu-item-select">
                            <span v-for="value,key in brushColor" v-on:click="setBrushColor(key)"><i class="color" v-bind:class="key"></i></span>
                        </span>
                    </div>
                    <div class="menu-item" v-bind:class="{ active: tool == 'size' }">
                        <span class="menu-item-group" v-on:click="active('size')">
                            <span class="size-1" v-bind:class="{ show: brush.size == '1' }"><icon class="icon" name="size"></icon></span>
                                          <span class="size-2" v-bind:class="{ show: brush.size == '2' }"><icon class="icon" name="size"></icon></span>
                                          <span class="size-3" v-bind:class="{ show: brush.size == '3' }"><icon class="icon" name="size"></icon></span>
                                          <span class="size-4" v-bind:class="{ show: brush.size == '4' }"><icon class="icon" name="size"></icon></span>
                                          <span class="size-5" v-bind:class="{ show: brush.size == '5' }"><icon class="icon" name="size"></icon></span>
                        </span>
                        <span class="menu-item-select">
                            <span v-for="value,key in brushSize" v-bind:class="'size-'+ key" v-on:click="setBrushSize(key)"><icon class="icon" name="size"></icon></span>
                        </span>
                    </div>
                    <div class="menu-item" v-bind:class="{ active: tool == 'brush' }">
                        <span class="menu-item-group" v-on:click="active('brush')">
                            <span v-bind:class="{ show: brush.attr == 'pencil' }"><icon class="icon" name="pencil" scale="20"></icon></span>
                                          <span v-bind:class="{ show: brush.attr == 'eraser' }"><icon class="icon" name="eraser" scale="20"></icon></span>
                            <span v-bind:class="{ show: brush.attr == 'text' }"><icon class="icon" name="text" scale="20"></icon></span>
                        </span>
                        <span class="menu-item-select">
                            <span v-on:click="setBrushAttr('pencil')"><icon class="icon" name="pencil" scale="20"></icon></span>
                            <span v-on:click="setBrushAttr('eraser')"><icon class="icon" name="eraser" scale="20"></icon></span>
                            <span v-on:click="setBrushAttr('text')"><icon class="icon" name="text" scale="20"></icon></span>
                            <span @click="trigger"><icon class="icon" name="picture" scale="20"></icon></span>
                        </span>
                    </div>
                    <div class="menu-item">
                        <span class="link"><icon class="icon" name="reset" scale="20"></icon></span>
                    </div>
                </div>
            </div>
        </div>
        <div class="canvas-container" id="canvas-container">
      <div id="img-wrap" class="img-wrap">
          <span class="br"></span>
          <span class="bl"></span>
          <span class="tr"></span>
          <span class="tl"></span>
          <button class="bt1">左转</button>
          <button class="bt3" id="bt3">确定</button>
          <button class="bt2">右转</button>
      </div>
      <textarea id="target" rows="" cols="" placeholder=""></textarea>
      <input id="myfile" type="file" accept="image/*"/>
            <canvas class="board" id="myCanvas" resize="true"></canvas>
        </div>
    </div>
</template>

<script>
    export default {
        name: 'whiteboard',
        paperPath: null,
        data () {
            return {
                msg: 'Welcome to WhiteBoard',
                inp:'Type here',
                tool: null,
                brush: {
                    attr: "pencil",
                    color: "black",
                    size: 2,
                    cap: "round",
                    selected: true
                },
                brushColor: {
                              black: "#000000",
                    red: "#f44336",
                    green: "#4caf50",
                    blue: "#2196f3",
                              yellow: "#ffc107",
                              violet: "#9c27b0",
                              rose: "#e91e63",
                              brown: "#795548"
                },
                        brushSize: {
                              1: 4,
                    2: 8,
                    3: 12,
                    4: 16,
                    5: 20,
                },
                brushAttr: {
                    pencil: "pencil",
                    eraser: "eraser",
                    //clear: "clear",
                    text: "text",
                    picture: "picture"
                },
                drawData: {
                    brush: 'null',
                    point: []
                }
            }                                          //问题1：包裹div如何每次自适应添加的图片大小，也就是清除记录上次的图片最终的大小
        },                                             //问题2：同一张图片不能连续上传问题，需要传一张别的才行
        mounted: function() {                         //问题3：传完小图再传大图，图片缩放记录的值有问题，跟问题1关联
            this.init();                               //问题4：添加图片和文字的位置问题，直接添加或旋转后添加位置不是很准确
            //文字输入框自适应高度                      //问题5：添加文字后修改，颜色和尺寸会变为当前选中状态，而非历史状态
            var addHandler = window.addEventListener ? function(elem,event,handler){elem.addEventListener(event,handler);}:function(elem,event,handler){elem.attachEvent("on"+event,handler);};
            var $ = function(id){return document.getElementById(id);}
            function autoTextArea(elemid){
                //新建一个textarea用户计算高度
                if(!$("_textareacopy")){
                    var t = document.createElement("textarea");
                    t.id="_textareacopy";
                    t.style.position="absolute";
                    t.style.left="-9999px";
                    document.body.appendChild(t);
                }
                function change(){
                    $("_textareacopy").value= $(elemid).value;
                    $(elemid).style.height= $("_textareacopy").scrollHeight+$("_textareacopy").style.height+"px";
                }
                addHandler($("target"),"propertychange",change);//for IE
                addHandler($("target"),"input",change);// for !IE
                $(elemid).style.overflow="hidden";//一处隐藏，必须的。
                $(elemid).style.resize="none";//去掉textarea能拖拽放大/缩小高度/宽度功能
            }
            addHandler(window,"load",function(){
                autoTextArea("target");
            });

            //图片移动缩放
            var oDiv = document.getElementById('img-wrap');
            oDiv.ondragstart=function (){         //阻止浏览器默认拖动事件
                return false
            }
            var aSpan = oDiv.getElementsByTagName('span');
            for (var i = 0; i < aSpan.length; i++) {
                dragFn(aSpan[i]);                      //给四个角添加缩放事件
            }
          oDiv.onmousedown=function(event){
              event.stopPropagation();
              var disX = event.clientX - oDiv.offsetLeft;
              var disY = event.clientY - oDiv.offsetTop;
              document.onmousemove=function (event)          //包裹图片div的拖动事件
              {
                  oDiv.style.left = event.clientX -disX+"px";
                  oDiv.style.top = event.clientY -disY+"px";
              }
              document.onmouseup=function()
              {
                  document.onmousemove=null;
                  document.onmouseup=null;
              }
          }
          function dragFn(obj) {
            obj.onmousedown = function (ev) {       //控制4个角的缩放函数，可以不等比例缩放，为了方便还是改为等比例
              var oEv = ev || event;                //使用raster.size = new Size(x,y)，可以解决非等比例缩放
              oEv.stopPropagation();
              var oldWidth = oDiv.offsetWidth;
              var oldHeight = oDiv.offsetHeight;
              var oldX = oEv.clientX;
              var oldY = oEv.clientY;
              var oldLeft = oDiv.offsetLeft;
              var oldTop = oDiv.offsetTop;

              document.onmousemove = function (ev) {
                var oEv = ev || event;
                oEv.stopPropagation();
                if (obj.className == 'tl') {
                  oEv.stopPropagation();
                  oDiv.style.width = oldWidth - (oEv.clientX - oldX) + 'px';
                  oDiv.style.height=oldHeight-(oEv.clientY-oldY)+'px';
                  oDiv.style.left = oldLeft + (oEv.clientX - oldX) + 'px';
                  oDiv.style.top = oldTop + (oEv.clientY - oldY) + 'px';
                }
                else if (obj.className == 'bl') {
                  oEv.stopPropagation();
                  oDiv.style.width = oldWidth - (oEv.clientX - oldX) + 'px';
                  oDiv.style.height=oldHeight+(oEv.clientY-oldY)+'px';
                  oDiv.style.left = oldLeft + (oEv.clientX - oldX) + 'px';
                  oDiv.style.bottom = oldTop + (oEv.clientY + oldY) + 'px';
                }
                else if (obj.className == 'tr') {
                  oEv.stopPropagation();
                  oDiv.style.width = oldWidth + (oEv.clientX - oldX) + 'px';
                  oDiv.style.height = oldHeight - (oEv.clientY - oldY)+'px';
                  oDiv.style.right = oldLeft - (oEv.clientX - oldX) + 'px';
                  oDiv.style.top = oldTop + (oEv.clientY - oldY) + 'px';
                }
                else if (obj.className == 'br') {
                  oEv.stopPropagation();
                  oDiv.style.width = oldWidth + (oEv.clientX - oldX) + 'px';
                  oDiv.style.height = oldHeight + (oEv.clientY - oldY)+'px';
                  oDiv.style.right = oldLeft - (oEv.clientX - oldX) + 'px';
                  oDiv.style.bottom = oldTop + (oEv.clientY + oldY) + 'px';
                }
              };
              document.onmouseup = function () {
                oEv.stopPropagation();
                document.onmousemove = null;
              };
              return false;
            };
          };
        },
        methods: {
            init() {
                var textctr = true;
                var imgctr = false;
                var num = 0;    //记录div旋转的值
                var shuzi = 0;  //记录添加图片的div
//                var hideImage = document.getElementById("hide");
                var inputObj = document.getElementById("myfile"); //取得输入框id
                var imgWrap = document.getElementById("img-wrap"); //包裹图片div的id
                inputObj.addEventListener('change',readFile,false); //输入框变化时触发
                //inputObj.click();
                function readFile(){
                    //var rf = 0;
                    var file = this.files[0];  //获取input上传的图片
                    if(!/image\/\w+/.test(file.type)){   //判断类型
                        alert("请确保文件为图像类型");
                        return false;
                    } //判断是否图片，在移动端由于浏览器对调用file类型处理不同
                    var reader = new FileReader();
                    reader.readAsDataURL(file);  //转化成base64数据类型
                    reader.onload = function(e){
                      var img = new Image();     //创建图像
                      shuzi+=1;
                      $("#img-wrap").css("display","block"); //显示包裹图片的div
                      img.id = "img"+shuzi;
                      img.src = this.result;  //把取到的src赋值给图片
                      imgWrap.appendChild(img);  //把图片添加到包裹的div
                      var oldW = $("img").width();  //记录的传入图片尺寸
                      var oldH = $("img").height();

                      function myf(){
                        var newX = event.clientX;  //document点击的位置
                        var newY = event.clientY;
                        var newW = $("img").width(); //缩放后的图片尺寸
                        var newH = $("img").height();
                        this.paperPath = new Path();  //点击确定 添加到paper
                        var raster = new Raster(img.id); //把图片的id传入
                        raster.rotate(num);
                        raster.position = new Point(newX-100,newY-20)
                        raster.on('load', function() {
                          raster.size = new Size(newW, newH);
                        });
                        $("#img-wrap img").css("display","none")  //隐藏添加到包裹div中的图片
                        $("#img-wrap").css({"width":"auto","height":"auto"})
                        $("#img-wrap").hide() //隐藏包裹图片的div
                        myf = null;   //清除事件，貌似没效果
                        num = 0;      //清空记录旋转角度的值
                        $("#img-wrap").css("transform","rotate(0)")  //复原包裹图片div旋转的角度
                      }
                    var bt3 = document.getElementById("bt3");  //给确认按钮添加事件
                      bt3.onclick = myf;

                      $(".bt1").click(function(){
                          num+=15;
                        $("#img-wrap").css("transform","rotate(" + num + "deg)")
                      })                                       //控制左右旋转的按钮
                      $(".bt2").click(function(){
                        num-=15;
                        $("#img-wrap").css("transform","rotate(" + num + "deg)")
                      })
                    }
                }


                // 初始化画布
                paper.install(window);
                var canvas = document.getElementById('myCanvas');
                paper.setup(canvas);
                // 开始绘画
                var self = this;
                var tools = new Tool();
                tools.onMouseDown = function(event) {
                   // start = event.point;
                    self.createDraw(self.brush);
                    self.draw(event.point.x, event.point.y);
                    self.drawData.brush = self.brush;
                    self.drawData.point.push({
                        x: event.point.x,
                        y: event.point.y
                    });
                }
                tools.onMouseDrag = function(event) {
                    //console.log(event.delta);
                    self.draw(event.point.x, event.point.y);
                    self.drawData.point.push({
                        x: event.point.x,
                        y: event.point.y
                    });
                }
                tools.onMouseUp = function(event) {
                    self.sendPoint();
                }
                $("#canvas-container").click(function() {
                    self.tool = null;
                });
                /*
                var self = this;
                $("#test-get").click(function() {
                    self.brush.color = "red";
                    self.createDraw(self.brush);
                    //console.log(JSON.stringify(self.point));
                    $.each(self.point, function(index, data) {
                        self.draw(data.x, data.y);
                    });
                });
                */
            },
            createDraw(param) {
                switch(param.attr) {
                    case "pencil":
                        this.paperPath = new Path();
                        this.paperPath.strokeColor = this.brushColor[param.color];
                        this.paperPath.strokeWidth = this.brushSize[param.size];
                        this.paperPath.strokeCap = param.cap;
                        //this.paperPath.selected = param.selected; // 显示节点
                        break;
                    case "eraser":
                        this.paperPath = new Path();
                        this.paperPath.strokeColor = "#FFFFFF";
                        this.paperPath.strokeWidth = this.brushSize[param.size];
                        this.paperPath.strokeCap = param.cap;
                        break;
                    case "clear":
                        /*
                        this.paperPath = new Path();
                        this.paperPath.strokeColor = "red";
                        this.paperPath.strokeWidth = 2;
                        this.paperPath.closed = true; // 封闭
                        */
                        break;
                    case "text":
                        if(this.textctr){
                            var x = event.clientX-85;
                            var y = event.clientY-10;
                            this.paperPath = new Path();
                            $("#target").css({
                                "display": "block",
                                "left":x+"px",
                                "top":y+"px",
                                "color": this.brushColor[param.color],
                                "font-size":this.brushSize[param.size]+"px",
                            })
                            $('#target').focus();
                            this.textctr = !this.textctr;
                        }
                        else{
                            if($('#target').val()!=""){                    //判断输入框值是否为空
                                var Left = $("#target").position().left;
                                var Top = $("#target").position().top+15;
                                var text = $('#target').val();
                                var Textobj = {
                                    point: [Left,Top],
                                    content: text,
                                    fillColor: this.brushColor[param.color],
                                    fontSize: this.brushSize[param.size],
                                }
                                var pointText = new paper.PointText(Textobj);
                                $('#target').val("")
                                var color = this.brushColor[param.color];
                                pointText.onMouseEnter = function(event){
                                    this.fillColor = "red"
                                }
                                pointText.onMouseLeave = function(event){
                                    this.fillColor = color
                                }
                                pointText.onClick = function(event){
                                    $('#target').css("display","block");
                                    $('#target').val(this.content);
                                    this.remove();
                                 }
                            }
                            this.textctr = !this.textctr;
                            $('#target').css("display","none")
                        }
                        break;

                    case "picture":
//                        this.paperPath = new Path();
//                        var raster = new Raster('hideImage');
////                      raster.position = new Point(300, 500)
////                        raster.scale(0.5);
//                        raster.position = view.center;
////                        raster.rotate(45);
                        break;
                }
            },
            draw(x, y) {
                var myPoint = new Point(x, y);
                this.paperPath.add(myPoint);
                this.paperPath.smooth();
            },
            sendPoint() {
                var point = JSON.stringify(this.point);
                //console.log(point);
                //this.point = [];
            },
            setBrushColor(value) {
                this.brush.color = value;
                this.tool = null;
            },
            setBrushAttr(value) {
                this.brush.attr = this.brushAttr[value];
                this.tool = null;
            },
            setBrushSize(value) {
                this.brush.size = value;
                this.tool = null;
            },
            active(value) {
                if (this.tool == value) {
                    this.tool = null;
                } else {
                    this.tool = value;
                }
            },
          trigger(){
              $("#myfile").trigger("click");
          },
    }
    }
</script>

<style>
    @import "../style/whiteboard.css";
</style>
